<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/25
 * Time: 11:20
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Assn extends Base
{
    /**
     * 社团首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $assn_type = input('assn_type');
            $assn_is_first = input('assn_is_first');
            $assn_name = trim(input('assn_name'), ' ');
            $sc_name = trim(input('sc_name'), ' ');
            $where['assn_status'] = 1;
            
            // 类型
            if(isset($assn_type) && $assn_type != ''){
                $where['assn_type'] = $assn_type;
            }
            // 是否双一流
            if(isset($assn_is_first) && $assn_is_first != ''){
                $where['assn_is_first'] = $assn_is_first;
            }
            // 社团名
            if(isset($assn_name) && $assn_name != ''){
                $where['assn_name'] = ['like', '%' . $assn_name . '%'];
            }
            //学校名
            if(isset($sc_name) && $sc_name != ''){
                $where['sc_name'] = ['like', '%' . $sc_name . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_assn')
                ->join('up_school', 'assn_school = sc_id', 'left')
                ->join('up_area ua1', 'ua1.district_id = assn_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = assn_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = assn_qu', 'left')
                ->where($where)
                ->count();// 获取总条数
            // 获取id，用于全部导出
            $count2 = Db::table('up_assn')
                ->join('up_school', 'assn_school = sc_id', 'left')
                ->join('up_area ua1', 'ua1.district_id = assn_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = assn_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = assn_qu', 'left')
                ->where($where)
                ->column('assn_id');
            $lists = Db::table('up_assn')
                ->join('up_school', 'assn_school = sc_id', 'left')
                ->join('up_area ua1', 'ua1.district_id = assn_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = assn_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = assn_qu', 'left')
                ->field('assn_id, assn_type, assn_user_id, assn_name, assn_image, sc_name, assn_school_qu, 
                assn_teacher, assn_company, assn_address, assn_time, assn_is_first,
                ua1.district as sheng, ua2.district as shi, ua3.district as qu')
                ->where($where)
                ->page($Nowpage, $limits)
                ->order('assn_time desc')
                ->select();
            // 团长名称
            foreach($lists as $k => $v){
                $user_name = Db::table('up_u_user')
                    ->where('user_id', 'IN', $v['assn_user_id'])
                    ->where('user_status', 'NEQ', 3)
                    ->column('user_username');
                $lists[$k]['user_name'] = implode(',', $user_name);
            }
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 添加社团
     * @return mixed|\think\response\Json
     */
    public function assnAdd(){
        if(Request::instance()->isPost()){
            $assn_name = trim(input('assn_name'), ' '); // 社团名称
            $assn_image = input('assn_image'); // logo
            $assn_is_first = input('assn_is_first'); // 是否双一流
            $assn_type = input('assn_type'); // 社团类型
            $assn_school = input('assn_school'); // 所属学校
            $assn_school_qu = trim(input('assn_school_qu'), ' '); // 校区
            $assn_user_id = input('assn_user_id'); // 社团长
            $assn_address = trim(input('assn_address'), ' '); // 办公中心
            $assn_teacher = trim(input('assn_teacher'), ' '); // 指导老师
            $assn_company = trim(input('assn_company'), ' '); // 指导单位
            $assn_join = input('assn_join'); // 社团新招
            $province = input('province');
            $city = input('city');
            $district = input('district');
            if($province == '' || $city == '' || $district == ''){
                return json(['code' => 100, 'msg' => '请选择地区']);
            }
            
            if(empty($assn_user_id)) return json(['code' => 100, 'msg' => '必须选的社团团长']);
            if(empty($assn_image)) return json(['code' => 100, 'msg' => '请上传logo']);
            
            $is_have_info = Db::table('up_staff')
                ->where('staff_user_id', $assn_user_id)
                ->where('staff_status', 2)
                ->where('staff_type', 1)
                ->where('staff_soldier_type', $assn_type)
                ->find();
            if(!$is_have_info) return json(['code' => 100, 'msg' => '无该用户的申请信息']);
            
            // 社团去重
            $isHave = Db::table('up_assn')
                ->where('assn_type', $assn_type)
                ->where('assn_name', $assn_name)
                ->where('assn_school', $assn_school)
                ->where('assn_school_qu', $assn_school_qu)
                ->find();
            if($isHave) return json(['code' => 100, 'msg' => '已有相同社团']);
            
            Db::startTrans();
            try{
                // 存入社团表
                $insert = [
                    'assn_type' => $assn_type,
                    'assn_name' => $assn_name,
                    'assn_image' => $assn_image,
                    'assn_school' => $assn_school,
                    'assn_school_qu' => $assn_school_qu,
                    'assn_teacher' => $assn_teacher,
                    'assn_company' => $assn_company,
                    'assn_address' => $assn_address,
                    'assn_join' => $assn_join,
                    'assn_update_time' => date('Y-m-d H:i:s'),
                    'assn_time' => date('Y-m-d H:i:s'),
                    'assn_is_first' => $assn_is_first,
                    'assn_sheng' => $province,
                    'assn_shi' => $city,
                    'assn_qu' => $district,
                ];
                $user_array = explode(',', $assn_user_id);
                if(!empty($assn_user_id)){
                    $insert['assn_user_id'] = $assn_user_id;
                    $insert['assn_number'] = count($user_array);
                }
                // 如果是军事类，则需把教员代码更新到社团
                if($is_have_info['staff_soldier_type'] == 1){
                    $insert['assn_code'] = $is_have_info['staff_instr_code'];
                }
                $assn_id = Db::table('up_assn')->insertGetId($insert);
                
                // 更新社团成员表
                if(!empty($assn_user_id)){
                    $inserts = [];
                    for($i = 0; $i < count($user_array); $i++){
                        $inserts[$i] = [
                            'am_assn_id' => $assn_id,
                            'am_user_id' => $user_array[$i],
                            'am_user_type' => 2,
                            'am_time' => date('Y-m-d H:i:s'),
                            'am_status' => 2
                        ];
                    }
                    Db::table('up_assn_member')->insertAll($inserts);
                }
                
                // 插入教员成员表
                $info = Db::table('up_staff')
                    ->where('staff_user_id', $assn_user_id)
                    ->where('staff_type', 1)
                    ->where('staff_soldier_type', $assn_type)
                    ->find();
                $staff_insert = [
                    'staff_type' => 2,
                    'staff_soldier_type' => $info['staff_soldier_type'],
                    'staff_school_id' => $assn_school,
                    'staff_assn_name' => $info['staff_assn_name'],
                    'staff_name' => '', // 手动填写的姓名
                    'staff_assn_id' => $assn_id,
                    'staff_gender' => $info['staff_gender'],
                    'staff_birthday' => $info['staff_birthday'],
                    'staff_user_card' => '', // 身份证号
                    'staff_politics' => $info['staff_politics'],
                    'staff_assn_duty' => $info['staff_assn_duty'],
                    'staff_faculty' => $info['staff_faculty'],
                    'staff_in_assn_time' => '', // 加入社团时间
                    'staff_old_troops' => $info['staff_old_troops'],
                    'staff_specilay' => $info['staff_specilay'],
                    'staff_phone' => $info['staff_phone'],
                    'staff_sign' => $info['staff_sign'],
                    'staff_sign_time' => $info['staff_sign_time'],
                    'staff_insert_time' => date('Y-m-d H:i:s'),
                    'staff_user_id' => $assn_user_id,
                    'staff_status' => 2
                ];
                
                // =============== 如果是军事类，则生成成员代码
                if($assn_type == 1){
                    // 学校代码
                    $school_code = Db::table('up_school')
                        ->where('sc_id', $assn_school)
                        ->value('sc_code');
    
                    // 年+月
                    $date = date('Ym');
                    $date_str = substr($date, 2, 4);
    
                    // 成员序号
                    $code = Db::table('up_about')->where('about_id', 1)->value('about_content');
                    $new_code = trim($code, ',');
                    $staff_member_code = $school_code . $date_str . $new_code . 'JY';
                    $staff_insert['staff_member_code'] = $staff_member_code;
    
                    // 更新教员序号
                    $update_code = $new_code + 1;
                    $zero = '';
                    $leng = strlen($update_code);
                    if($leng < 6){
                        for($i = $leng; $i<6; $i++){
                            $zero .= '0';
                        }
                    }
                    $about_code = ',' . $zero . $update_code . ',';
                    Db::table('up_about')->where('about_id', 1)->update(['about_content' => $about_code]);
                }
                $assn_id = Db::table('up_staff')->insertGetId($staff_insert);
                
                Db::commit();
                $res = 1;
            }catch(\Exception $e){
                Db::rollback();
                $res = 2;
            }
            
            if($res == 1){
                $school_name = Db::table('up_school')
                    ->where('sc_id', $assn_school)
                    ->value('sc_name');
                $str = $school_name . $assn_name . '社团创建啦！';
                $this->Jpush(2, '', $str, ['assn_id' => $assn_id, 'send_type' => 16]);
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        // 学校
        $school = Db::table('up_school')
            ->where('sc_status', 1)
            ->field('sc_id, sc_name')
            ->select();
        // 用户
        $user = Db::table('up_u_user')
            ->where('user_status', 1)
            ->field('user_id, user_username, user_phone')
            ->select();
        $province = Db::table('up_area')->where('level', 1)->select();
        $this->assign([
            'school' => $school,
            'user' => $user,
            'province' => $province
        ]);
        return $this->fetch('assn/assnadd');
    }
    
    /**
     * 编辑社团
     * @return mixed|\think\response\Json
     */
    public function assnEdit(){
        if(Request::instance()->isPost()){
            $id = input('assn_id');
            $assn_name = trim(input('assn_name'), ' '); // 社团名称
            $assn_image = input('assn_image'); // logo
            $assn_is_first = input('assn_is_first'); // 是否双一流
            $assn_type = input('assn_type'); // 社团类型
            $assn_school = input('assn_school'); // 所属学校
            $assn_school_qu = trim(input('assn_school_qu'), ' '); // 校区
            $assn_user_id = input('assn_user_id'); // 社团长
            $assn_address = trim(input('assn_address'), ' '); // 办公中心
            $assn_teacher = trim(input('assn_teacher'), ' '); // 指导老师
            $assn_company = trim(input('assn_company'), ' '); // 指导单位
            $assn_join = input('assn_join'); // 社团新招
            $province = input('province');
            $city = input('city');
            $district = input('district');
            if($province =='' || $city == '' || $district == ''){
                return json(['code' => 100, 'msg' => '请选择地区']);
            }
    
            if(empty($assn_user_id)) return json(['code' => 100, 'msg' => '必须选的社团团长']);
            // 社团去重
            $isHave = Db::table('up_assn')
                ->where('assn_type', $assn_type)
                ->where('assn_name', $assn_name)
                ->where('assn_school', $assn_school)
                ->where('assn_school_qu', $assn_school_qu)
                ->where('assn_id', 'NEQ', $id)
                ->find();
            if($isHave) return json(['code' => 100, 'msg' => '已有相同社团']);
            
            Db::startTrans();
            try{
                $update = [
                    'assn_type' => $assn_type,
                    'assn_name' => $assn_name,
                    'assn_school' => $assn_school,
                    'assn_school_qu' => $assn_school_qu,
                    'assn_teacher' => $assn_teacher,
                    'assn_company' => $assn_company,
                    'assn_address' => $assn_address,
                    'assn_join' => $assn_join,
                    'assn_update_time' => date('Y-m-d H:i:s'),
                    'assn_is_first' => $assn_is_first,
                    'assn_sheng' => $province,
                    'assn_shi' => $city,
                    'assn_qu' => $district
                ];
                if(!empty($assn_image)){
                    $update['assn_image'] = $assn_image;
                }
                
                // 判断是否修改了团长
                $assn_info = Db::table('up_assn')
                    ->field('assn_user_id')
                    ->where('assn_id', $id)
                    ->find();
                
                //---------------------- 如果修改了社团长，则需更新以下表 -------------------//
                if($assn_info['assn_user_id'] != $assn_user_id){
                    // 删除社团成员表里该社团的所有团长
                    Db::table('up_assn_member')
                        ->where('am_assn_id', $id)
                        ->where('am_user_type', 2)
                        ->delete();
                    
                    $user_array = explode(',', $assn_user_id);
                    if(!empty($assn_user_id)){ // 选择了社团长
                        // 插入社团成员表
                        $insert = [];
                        for($i = 0; $i < count($user_array); $i++){
                            $res_2 = Db::table('up_assn_member')
                                ->where('am_assn_id',$id)
                                ->where('am_user_id',$user_array[$i])
                                ->find();
                            if($res_2){
                                Db::table('up_assn_member')
                                    ->where('am_assn_id',$id)
                                    ->where('am_user_id',$user_array[$i])
                                    ->update(['am_user_type'=>2,'am_status'=>2]);
                            }else{
                                $insert[$i] = [
                                    'am_assn_id' => $id,
                                    'am_user_id' => $user_array[$i],
                                    'am_user_type' => 2,
                                    'am_time' => date('Y-m-d H:i:s'),
                                    'am_status' => 2
                                ];
                            }
                        }
                        if($insert){
                            Db::table('up_assn_member')->insertAll($insert);
                        }
                        // 社团表团长字段
                        $update['assn_user_id'] = $assn_user_id;
                    }else{ // 没有选团长
                        $update['assn_user_id'] = null;
                    }
                    
                    //社团消息表
                    $is_in = Db::table('up_notice_assn')
                        ->where('n_assn_id', $id)
                        ->where('n_audit_status', 1)
                        ->find();
                    if($is_in){
                        $update_notice['n_assn_manage'] = ',' . $assn_user_id . ',';
                        if(empty($assn_user_id)){
                            $update_notice['n_assn_manage'] = null;
                        }
                        // 社团消息表
                        Db::table('up_notice_assn')->where('n_assn_id', $id)->update($update_notice);
                    }
                    
                    // 社团表社团人数
                    $count = Db::table('up_assn_member')
                        ->where('am_assn_id', $id)
                        ->where('am_status', 2)
                        ->count();
                    $update['assn_number'] = $count;
                }
                // 更新社团表
                Db::table('up_assn')->where('assn_id', $id)->update($update);
                
                Db::commit();
                $res = 1;
            }catch(\Exception $e){
                Db::rollback();
                $res = 2;
            }
            
            if($res == 1){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $assn_id = input('assn_id');
        $assn = Db::table('up_assn')->where('assn_id', $assn_id)->find();
        // 学校
        $school = Db::table('up_school')
            ->where('sc_status', 1)
            ->field('sc_id, sc_name')
            ->select();
        // 本社团用户
        $user = Db::table('up_assn_member')
            ->join('up_u_user', 'user_id = am_user_id', 'left')
            ->where('am_assn_id', $assn_id)
            ->where('am_status', 2)
            ->field('user_id, user_username, user_phone')
            ->select();
        $province = Db::table('up_area')->where('level', 1)->select();
        $city = Db::table('up_area')->where('pid', $assn['assn_sheng'])->select();
        $district = Db::table('up_area')->where('pid', $assn['assn_shi'])->select();
        $this->assign([
            'school' => $school,
            'user' => $user,
            'assn' => $assn,
            'assn_id' => $assn_id,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);
        return $this->fetch('assn/assnedit');
    }
    
    /**
     * 删除社团
     * @return \think\response\Json
     */
    public function assnDel(){
        $assn_id = input('id');
        $res = Db::table('up_assn')->delete($assn_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 社团文件列表
     * @return mixed|\think\response\Json
     */
    public function assnFiles(){
        if(request()->isAjax ()){
            $where['af_assn_id'] = session('assn_id');
            $af_type = input('af_type');
            // 文件类型
            if(isset($af_type) && $af_type != ''){
                $where['af_type'] = $af_type;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_assn_files')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_assn_files')
                ->field('af_id, af_assn_url, af_type, af_name, af_time')
                ->where($where)
                ->page($Nowpage, $limits)
                ->order('af_time desc')
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $assn_id = input('assn_id');
        session('assn_id', $assn_id);
        return $this->fetch('assn/assnfiles');
    }
    
    /**
     * 下载文件
     */
    public function assnFilesDown(){
        $af_id = input('af_id');
        $url = Db::table('up_assn_files')->where('af_id', $af_id)->value('af_assn_url');
        // 路径是否为空
        if(!empty($url)){
            $header = get_headers($url, true); // 获取文件返回的HTTP_CODE是200或304
            // 判断文件是否存在
            if(isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'))){
                $exe = explode('.', $url);
                $exe = end($exe);
                $date=date("YmdHis");
                ob_start();
                header( "Content-type:application/octet-stream");
                header( "Accept-Ranges:bytes");
                header( "Content-Disposition:attachment;filename={$date}.{$exe}");
                $size=readfile($url);
                header( "Accept-Length:".$size);
                ob_end_flush();
            }else{
                return json(['code' => 100, 'msg' => $header[0]]);
            }
        }else{
            return json(['code' => 100, 'msg' => '文件路径错误']);
        }
    }
    
    /**
     * 删除文件
     * @return \think\response\Json
     */
    public function assnFilesDel(){
        $af_id = input('id');
        $res = Db::table('up_assn_files')->where('af_id', $af_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
    
        }
    }
    
    /**
     * 社团成员列表
     * @return mixed|\think\response\Json
     */
    public function assnUser(){
        if(request()->isAjax ()){
            $where['am_assn_id'] = session('assn_id');
            $where['am_status'] = 2;
            $am_user_type = input('am_user_type');
            $user_name = trim(input('user_username'), ' ');
            // 成员类型
            if(isset($am_user_type) && $am_user_type != ''){
                $where['am_user_type'] = $am_user_type;
            }
            // 成员名称
            if(isset($user_name) && $user_name != ''){
                $where['user_username'] = ['like', '%' . $user_name . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_assn_member')
                ->join('up_u_user', 'user_id = am_user_id', 'left')
                ->where($where)
                ->count();// 获取总条数
            // 用于全部导出
            $count2 = Db::table('up_assn_member')
                ->join('up_u_user', 'user_id = am_user_id', 'left')
                ->where($where)
                ->column('am_id');
            $lists = Db::table('up_assn_member')
                ->join('up_u_user', 'user_id = am_user_id', 'left')
                ->field('am_id, am_user_type, user_username, user_phone, am_time')
                ->where($where)
                ->page($Nowpage, $limits)
                ->order('am_time desc')
                ->select();
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);
        }
        $assn_id = input('assn_id');
        session('assn_id', $assn_id);
        return $this->fetch('assn/assnuser');
    }
    
    /**
     * 导出社团
     * @return \think\response\Json
     */
    public function assnOut(){
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '请选择社团']);
        }
        $where['assn_id'] = array('IN',$ids);
        $lists = Db::table('up_assn')
            ->join('up_school', 'sc_id = assn_school', 'left')
            ->join('up_area ua1', 'ua1.district_id = assn_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = assn_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = assn_qu', 'left')
            ->where($where)
            ->field('assn_id, assn_type, assn_name, sc_name, assn_school_qu, assn_teacher, 
            assn_company, assn_address, assn_number, assn_time, assn_is_first, ua1.district as sheng, 
            ua2.district as shi, ua3.district as qu, assn_code')
            ->select();
    
        foreach($lists as $key => $vo){
            //社团类型
            if($vo['assn_type'] == 1) $lists[$key]['assn_type'] = '国防军事类社团';
            if($vo['assn_type'] == 2) $lists[$key]['assn_type'] = '非国防军事类社团';
            
            // 是否双一流
            if($vo['assn_is_first'] == 1) $lists[$key]['assn_is_first'] = '双一流学校';
            if($vo['assn_is_first'] == 2) $lists[$key]['assn_is_first'] = '非双一流学校';
        }
    
        $cellname = [
            ['assn_id','社团ID',10,'LEFT'],
            ['assn_type','社团类型',20,'LEFT'],
            ['assn_name','社团名称',30,'LEFT'],
            ['sc_name','所在学校',30,'LEFT'],
            ['assn_school_qu','校区',20,'LEFT'],
            ['assn_teacher','指导老师',20,'LEFT'],
            ['assn_company','指导单位',30,'LEFT'],
            ['assn_address','社团地址',40,'LEFT'],
            ['assn_number','社团人数',15,'LEFT'],
            ['assn_time','创建时间',20,'LEFT'],
            ['assn_is_first','是否双一流',20,'LEFT'],
            ['sheng','所在省',15,'LEFT'],
            ['shi','所在市',15,'LEFT'],
            ['qu','所在区',15,'LEFT'],
            ['assn_code','社团代码',25,'LEFT']
        ];
        $res = exportExcel('成员列表','Associations',$cellname,$lists);
        return json($res);
    }
    
    /**
     * 导出社团成员
     * @return \think\response\Json
     */
    public function assnUserOut(){
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '请选择成员']);
        }
        $where['am_id'] = array('IN',$ids);
        $lists = Db::table('up_assn_member')
            ->join('up_u_user', 'user_id = am_user_id', 'left')
            ->where($where)
            ->field('user_id, user_username, user_phone, am_user_type, am_time')
            ->select();
    
        foreach($lists as $key => $vo){
            //角色
            if($vo['am_user_type'] == 1) $lists[$key]['am_user_type'] = '普通成员';
            if($vo['am_user_type'] == 2) $lists[$key]['am_user_type'] = '社团管理员';
        }
    
        $cellname = [
            ['user_id','成员ID',10,'LEFT'],
            ['user_username','成员名称',50,'LEFT'],
            ['user_phone','手机号',20,'LEFT'],
            ['am_user_type','角色',20,'LEFT']
        ];
        $res = exportExcel('社团成员列表','Member',$cellname,$lists);
        return json($res);
    }
    
    // 踢除成员
    public function userOut(){
        
    }
}